package 线程;

import java.util.Random;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CyclicBarrierTest {
    static int threadNum = 5;
    static final String[] locations = {"A", "B", "C", "D", "E"};

    public static void main(String[] args) {
        Random rd = new Random();
        final CyclicBarrier cb = new CyclicBarrier(threadNum);
        ExecutorService ex = Executors.newFixedThreadPool(threadNum);

        for (int i = 0; i < threadNum; i++) {
            final int threadi = i;
            ex.submit(() -> {
                int k = 0;
                for (String name : locations) {
                    k++;
                    try {
                        Thread.sleep(rd.nextInt(5000));
                        System.out.println("线程：" + threadi + "已经到达目的" + name + "  已经到达目的地的线程还有：" + cb.getNumberWaiting());
                        cb.await();//等待其他人
                        if (k == threadNum && (cb.getNumberWaiting() == threadNum - 1)) {
                            System.out.println("所有线程已经完成本次赛跑！");
                            cb.reset();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
}
